import os
import re
from tkinter import filedialog


# n.nn-文件名(下载序列,Pn).后缀名  ===>  n*m-文件名.后缀名

# 指定执行
# 剔除指定字符串
def del_assign(assign_string, old_name):
    return old_name.replace(assign_string, '')


# 默认执行
def run():
    # 获取文件夹内所有文件的文件名
    path = filedialog.askdirectory()
    print(path)
    file_list = os.listdir(path)

    file_num = len(file_list)
    max_digit = len(str(file_num))

    for old_name in file_list:

        if old_name.index('.') != old_name.rindex('.'):

            loc1 = old_name.index('.')
            loc3 = old_name.rindex('(')
            loc4 = old_name.rindex('.')

            replenish_digit = max_digit - len(old_name[: loc1])

            max_index_long_string = old_name[loc1 + 1: loc1 + 2 + max_digit]
            # 提取所有数字字符串，以列表形式输入
            index_string = re.findall('(\d+)', max_index_long_string)[0]

            name1 = '0' * replenish_digit + old_name[: loc1] + '_'
            name2 = max_index_long_string.replace(index_string, '')
            name3 = old_name[loc1 + 2 + max_digit: loc3]
            name4 = old_name[loc4:]
            new_name = name1 + name2 + name3 + name4
            new_name = new_name.replace(name1 + '-', name1)
            new_name = new_name.replace(name1 + '_', name1)
            new_name = new_name.replace(name1 + ' ', name1)
            new_name = new_name.replace(name1 + '.', name1)

            old_file_name = path + os.sep + old_name
            new_file_name = path + os.sep + new_name
            print(old_name, '====>', new_name)
            os.renames(old_file_name, new_file_name)
        else:
            print("---> 无法修改 --->", old_name)


if __name__ == '__main__':

    run()
